﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using HZ.Supervise.IBLL;
using HZ.Supervise.Model;
using HZ.Supervise.Model.Enum;
using HZ.Supervise.Model.View; 
using System.Data;

namespace HZ.Supervise.Web.Report
{
    public partial class ReportByYaoZheng :BasePage
    {
        IBLL_Company ic = HZ.Supervise.BLLFactory.IBLL_Company();
        SuperviseQuery vs = new SuperviseQuery();

        public ReportByYaoZheng()
        {
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                this.AreaControl1.InitAreaID = CurrentAccount.GetUser().Org.Area.AreaID;
                BindData(); 
            }
        }

        /// <summary>
        /// 查询
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void AspNetPager_CompanyPS_PageChanged(object sender, EventArgs e)
        { 
            BindData();

        }

        /// <summary>
        /// 绑定数据 
        /// </summary>
        public void BindData()
        {
            vs = Queryby();
            vs.Flag = "0";
            int t = 0;
            System.Data.DataTable dt = ic.ReportByYaoZheng(vs, 1, 0, out t);
            DataTable dtArea = getAreaTable(dt);
            DataRow drtotal = dtArea.NewRow();
            drtotal["市、州"] = "总计";
            drtotal["医疗机构数量"] = dt.Compute("SUM([基层医疗机构数量])", "1=1");
            drtotal["区、县"] = " ";
            drtotal["基层医疗机构数量"] = dt.Compute("SUM([基层医疗机构数量])", "1=1");
            drtotal["网上采购数量"] = dt.Compute("SUM(网上采购数量)", "1=1");
            drtotal["未网上采购数量"] = dt.Compute("SUM([未网上采购数量])", "1=1");

            drtotal["网上采购机构所占比例"] = (Convert.ToDecimal(dt.Compute("SUM([网上采购数量])", "1=1")) / Convert.ToDecimal(dt.Compute("SUM([基层医疗机构数量])", "1=1"))).ToString("p2");
            drtotal["采购金额"] = dt.Compute("SUM([采购金额])", "1=1");
            drtotal["入库金额"] = dt.Compute("SUM([入库金额])", "1=1");
            drtotal["销售金额"] = dt.Compute("SUM([销售金额])", "1=1");
            drtotal["退货金额"] = dt.Compute("SUM([退货金额])", "1=1");
            drtotal["应缴款金额"] = dt.Compute("SUM([应缴款金额])", "1=1");
            dtArea.Rows.Add(drtotal);
            this.gvwReport.DataSource = dtArea;
            this.gvwReport.DataBind();
            GroupRows(gvwReport, 0);
            GroupRows(gvwReport, 1);
            GroupRows(gvwReport, 2);
            decimal a = Convert.ToDecimal(drtotal["入库金额"]) == 0 ? 1 : Convert.ToDecimal(drtotal["入库金额"]);
            a = Convert.ToDecimal(drtotal["采购金额"]) == 0 ? 1 : Convert.ToDecimal(drtotal["采购金额"]);
            string wareamount = "0.00%";
            //if (Convert.ToDecimal(drtotal["入库金额"]) == 0 || Convert.ToDecimal(drtotal["采购金额"]) == 0)
            //{
            //    wareamount = "0.00%";
            //}
            //else
            //{
            //    wareamount = (Convert.ToDecimal(drtotal["入库金额"]) / Convert.ToDecimal(drtotal["采购金额"])).ToString("P2");
            //}
            lblMemo.Text = string.Format("采购金额合计：{0}  入库金额合计：{1}  销售金额合计：{2}  退货金额合计：{3} 应缴款金额合计：{4}", 
                string.Format("{0:F}", Convert.ToDecimal(drtotal["采购金额"]) / 10000) + "万元",
                string.Format("{0:F}", Convert.ToDecimal(drtotal["入库金额"]) / 10000) + "万元"
                , string.Format("{0:F}", Convert.ToDecimal(drtotal["销售金额"]) / 10000) + "万元"
                , string.Format("{0:F}", Convert.ToDecimal(drtotal["退货金额"]) / 10000) + "万元"
                , string.Format("{0:F}", Convert.ToDecimal(drtotal["应缴款金额"]) / 10000) + "万元"
                );
        }
        protected void btnQuery_Click(object sender, EventArgs e)
        {
            BindData();
        }


        /// <summary>
        /// 合并列
        /// </summary>
        /// <param name="GridView1"></param>
        /// <param name="cellNum"></param>
        protected void GroupRows(GridView GridView1, int cellNum )
        {
            int i = 0, rowSpanNum = 1;
            while (i < GridView1.Rows.Count - 1)
            {
                GridViewRow gvr = GridView1.Rows[i];
                for (++i; i < GridView1.Rows.Count; i++)
                {
                    GridViewRow gvrNext = GridView1.Rows[i];
                    if (gvr.Cells[cellNum].Text == gvrNext.Cells[cellNum].Text)
                    {
                        gvrNext.Cells[cellNum].Visible = false;
                        //gvrNext.Cells[cellNum2].Visible = false;
                        rowSpanNum++;
                    }
                    else
                    {
                        gvr.Cells[cellNum].RowSpan = rowSpanNum;
                        //gvr.Cells[cellNum2].RowSpan = rowSpanNum;
                        rowSpanNum = 1;
                        break;
                    }
                    if (i == GridView1.Rows.Count - 1)
                    {
                        gvr.Cells[cellNum].RowSpan = rowSpanNum;
                        //gvr.Cells[cellNum2].RowSpan = rowSpanNum;
                    }
 
                }
            }
        }

 

        /// <summary>
        /// 导出 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnExcel_Click(object sender, EventArgs e)
        {
            //SuperviseQuery vs = new SuperviseQuery();
            vs = Queryby();
            vs.Flag = "0";
            int t = 0;
            System.Data.DataTable dt = ic.ReportByYaoZheng(vs, 1, 0, out t);
            //DataTable dttmp = dt.Compute("GROUP BY","faAreaID");
            DataView dv = dt.DefaultView;
            string startTime = "2011年10月24日";
            DateTime dtime =  System.DateTime.Now;
            string endTime = dtime.Year + "年" + dtime.Month + "月" + dtime.Day + "日";
            try
            {
               


            if (!string.IsNullOrEmpty(txtStratTime.Text.Trim()))
            {
                dtime = Convert.ToDateTime(txtStratTime.Text.Trim());
                startTime = dtime.Year + "年" + dtime.Month + "月" + dtime.Day + "日";
            }

            if (!string.IsNullOrEmpty(txtEndTime.Text .Trim ()))
            {

                dtime = Convert.ToDateTime(txtEndTime.Text.Trim());
                endTime = dtime.Year + "年" + dtime.Month + "月" + dtime.Day + "日";
            }

            }
            catch
            {
                HZ.Web.WebUtil.Alert("日期格式错误！请使用YYYY-MM-DD格式！", this);
                return;
            }
            DataTable dtArea = getAreaTable(dt);
            dtArea.Columns.Remove("AreaID");
            DataRow drtotal = dtArea.NewRow();
            drtotal["市、州"] = "总计";
            drtotal["医疗机构数量"] = dt.Compute("SUM([基层医疗机构数量])", "1=1");
            drtotal["区、县"] = " ";
            drtotal["基层医疗机构数量"] = dt.Compute("SUM([基层医疗机构数量])", "1=1");
            drtotal["网上采购数量"] = dt.Compute("SUM(网上采购数量)", "1=1");
            drtotal["未网上采购数量"] = dt.Compute("SUM([未网上采购数量])", "1=1");
           
            drtotal["网上采购机构所占比例"] =( Convert.ToDecimal(dt.Compute("SUM([网上采购数量])", "1=1")) / Convert.ToDecimal(dt.Compute("SUM([基层医疗机构数量])", "1=1"))).ToString("p2");
            drtotal["采购金额"] = dt.Compute("SUM([采购金额])", "1=1");
            drtotal["入库金额"] = dt.Compute("SUM([入库金额])", "1=1");
            drtotal["销售金额"] = dt.Compute("SUM([销售金额])", "1=1");
            drtotal["退货金额"] = dt.Compute("SUM([退货金额])", "1=1");
            drtotal["应缴款金额"] = dt.Compute("SUM([应缴款金额])", "1=1");
            dtArea.Rows.Add(drtotal);



            ExcelHelper.ExportByWeb(dtArea, "四川省医疗机构网上耗材采购情况汇总表", "四川省医疗机构网上耗材采购监测数据", startTime + "-" + endTime);
           
        }

        protected DataTable setColumnValue(DataTable dt)
        {
            foreach (DataRow dr in dt.Rows)
            { 
                
            }
            
            return dt;
        }
        protected DataTable getAreaTable(DataTable dt)
        { 
            dt.Columns.Remove("faAreaID");
            
            DataTable dtArea = dt.Clone(); 
            
            string fatherHosCount = string.Empty;
            //"长春市","吉林市","四平市","辽源市","通化市","白山市","松原市","白城市","延边朝鲜族自治州","吉林省长白山管委会"
            string[] fatherArea =new string[]{"长春市", "吉林市", "四平市", "辽源市", "通化市", "白山市", "松原市", "白城市", "延边朝鲜族自治州", "长白山管委会"};
            for (int i = 0; i < fatherArea.Length; i++)
            {
                DataTable dtTmp = new DataTable();
                dtTmp = dt.Clone();
                DataRow[] drs = dt.Select("[市、州]='" + fatherArea[i] + "'");
                if (drs.Length > 0)
                {
                    foreach (DataRow dr in drs)
                    {
                        dtTmp.ImportRow(dr);
                        fatherHosCount = dr["医疗机构数量"].ToString();
                    }

                    DataRow drtotal = dtTmp.NewRow();
                    drtotal["市、州"] = fatherArea[i].ToString();
                    drtotal["医疗机构数量"] = fatherHosCount;
                    drtotal["区、县"] = "小计";
                    drtotal["基层医疗机构数量"] = dtTmp.Compute("SUM([基层医疗机构数量])", "1=1");
                    drtotal["网上采购数量"] = dtTmp.Compute("SUM(网上采购数量)", "1=1");
                    drtotal["未网上采购数量"] = dtTmp.Compute("SUM([未网上采购数量])", "1=1");

                    drtotal["网上采购机构所占比例"] = (Convert.ToDecimal(dtTmp.Compute("SUM([网上采购数量])", "1=1")) / Convert.ToDecimal(dtTmp.Compute("SUM([基层医疗机构数量])", "1=1"))).ToString("p2");
                    drtotal["采购金额"] = dtTmp.Compute("SUM([采购金额])", "1=1");
                    drtotal["入库金额"] = dtTmp.Compute("SUM([入库金额])", "1=1");
                    drtotal["销售金额"] = dtTmp.Compute("SUM([销售金额])", "1=1");
                    drtotal["退货金额"] = dtTmp.Compute("SUM([退货金额])", "1=1");
                    drtotal["应缴款金额"] = dtTmp.Compute("SUM([应缴款金额])", "1=1");
                    dtTmp.Rows.Add(drtotal);
                    foreach (DataRow dr in dtTmp.Rows)
                    {

                        dtArea.ImportRow(dr);
                    }
                }
            }
           

            return dtArea;
        }


        protected void gvwInfo_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            Control cmdControl = e.CommandSource as Control;
            GridViewRow row = cmdControl.NamingContainer as GridViewRow;


            string sessionId = Guid.NewGuid().ToString();
            SuperviseQuery vs = new SuperviseQuery();
            //if (!string.IsNullOrEmpty(txtStratTime.Text))
            //{
            //    vs.CenSubmiitTimeFrom = Convert.ToDateTime(txtStratTime.Text.Trim());
            //}

            //if (!string.IsNullOrEmpty(txtEndTime.Text.Trim()))
            //{
            //    vs.CenSubmiitTimeTo = Convert.ToDateTime(txtEndTime.Text.Trim());
            //}
            vs = Queryby();
            HiddenField  hidArea= row.FindControl("hidAreaid") as HiddenField;
            vs.AreaID = HZ.Supervise.Web.Function.GetAreaIDBySQL( hidArea.Value);
            vs.AreaName = e.CommandArgument.ToString();

            if (e.CommandArgument.ToString() == "小计")
            {
                vs.AreaName = row.Cells[0].Text;
            }
            if (e.CommandArgument.ToString().Trim () == "")
            {
                vs.AreaName = "吉林省";
            }

            Session[sessionId] = vs;
            if (e.CommandName == "lbnPur")
            {

                Response.Redirect(string.Format("PurchaseNotNet.aspx?sesid={0}", sessionId));
            }

        }

        /// <summary>
        /// 查询条件
        /// </summary>
        /// <returns></returns>
        private SuperviseQuery Queryby()
        {
            //SuperviseQuery vs = new SuperviseQuery();


            //vs.SortFields = OrderFileds.SelectedValue + " " + OrderType.SelectedValue;
            //vs.CompanyName_PS = txtCompanyName_PS.Text.Trim();
            if (!string.IsNullOrEmpty(txtStratTime.Text))
            {
                vs.CenSubmiitTimeFrom = DateTime.Parse(txtStratTime.Text.Trim());

            }
            if (!string.IsNullOrEmpty(txtEndTime.Text))
            {
                vs.CenSubmiitTimeTo = Convert.ToDateTime(txtEndTime.Text.Trim());

            }
            if (!string.IsNullOrEmpty(ddlIsEss.SelectedValue))
            {
                vs.IsEssential = ddlIsEss.SelectedValue;
            }
            if (!string.IsNullOrEmpty(ddlIsGov.SelectedValue))
            {
                vs.IsGovernment = ddlIsGov.SelectedValue;
            }
            vs.AreaID = HZ.Supervise.Web.Function.GetAreaIDBySQL(AreaControl1.SelectedAreaID);
            vs.SortSource = Convert.ToInt32(ddlSortSource.SelectedValue);
            /*    TB_Hospital表中
                Levels表示医院等级：0 其他，1 一甲，2 一乙，3 二甲，4 二乙，5三甲，6 三乙
                IsCountry表示是否基层医疗机构：0 非基层医疗机构，1 基层医疗机构

                IsCountryDetail  1乡镇，2社区，3 民营，4 其他      
                 */
            switch (ddlHosType.SelectedValue)
            {
                case "0":
                    break;
                case "1":
                    vs.Levels = "'3','4','5','6'";
                    break;
                case "2":
                    vs.IsCountry = "'1','2','3','4'";
                    break;
                case "3":
                    vs.IsCountry = "'2'";
                    break;
                case "4":
                    vs.IsCountry = "'1'";
                    break;
                default:
                    break;
            }


            return vs;
        }

        /// <summary>
        /// 查询条件
        /// </summary>
        /// <returns></returns>
        //private SuperviseQuery Queryby()
        //{
        //    try
        //    {
        //        if (!string.IsNullOrEmpty(txtStratTime.Text.Trim()))
        //        {
        //            vs.CenSubmiitTimeFrom = DateTime.Parse(Convert.ToString(txtStratTime.Text.Trim()));

        //        }
        //        if (!string.IsNullOrEmpty(txtEndTime.Text.Trim()))
        //        {
        //            vs.CenSubmiitTimeTo = DateTime.Parse(Convert.ToString(txtEndTime.Text.Trim()));
        //        }
        //    }
        //    catch
        //    {
        //        HZ.Web.WebUtil.Alert("日期格式错误！请使用YYYY-MM-DD格式！", this);
        //    }


        //    return vs;
        //}


      

    }
}
